package com.fm.jbsql.entry;

import com.fm.jbsql.util.CmdOpt;
import com.fm.jbsql.util.JbsqlException;
import java.util.logging.*;

/**
 * Created by IntelliJ IDEA.
 * User: syaroshenko
 * Date: Jul 13, 2006
 * Time: 11:36:27 AM
 * Program entry point.
 */

/**
 * Program entry point.
 */
public final class Main {
    private static final Logger logger = Logger.getLogger("");
    private static FileHandler fh = null;

    /**
     * Program entry point.
     * @param args program input arguments
     */
    public static void main (String[] args) {
		try {
        	run(args);
        } catch (JbsqlException ex) {
	        System.exit(1);
		} catch ( Exception ex ) {
            ex.printStackTrace();
	        System.exit(1);
		}
        System.exit(0);
    }

    /**
     * Run project.
     * @param args program input arguments
     * @throws JbsqlException in case of wrong input arguments
     */
    public static void run(String[] args) throws Exception{
    	
        CmdOpt cmd = new CmdOpt();
        String sargs = "";
        for ( int loop = 0; loop < args.length; loop++ ) {
            sargs += args[loop];
            sargs += " ";            
        }
        if ( !cmd.parseCmdLine(args) ) throw new JbsqlException(null, null, new Exception("Invalid params for jbsql: <" + sargs + ">"));

        if ( cmd.getLevel() != Level.OFF ) {
			fh = new FileHandler("jbsql.log");
			fh.setFormatter(new SimpleFormatter());
			logger.addHandler(fh);
        }
        logger.setLevel(cmd.getLevel());
		try{
			ProjectManager mng = ProjectManager.getInstance();
			mng.run(cmd);
			
			if ( fh != null ) {
				fh.flush();
				fh.close();
				fh = null;
			}
		}catch(Exception e){
			if(cmd.getLevel() != Level.OFF) logger.log(Level.SEVERE, e.getMessage(), e);
			throw e;
		}
    }
}
